import os
import json
import codecs
import numpy as np
import matplotlib.pyplot as plt
BasePath = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")

top_categories_dict = {
    "location": ["location_traffic_convenience", "location_distance_from_business_district", "location_easy_to_find"],
    "service": ["service_wait_time", "service_waiters_attitude", "service_parking_convenience", "service_serving_speed"],
    "price": ["price_level", "price_cost_effective", "price_discount"],
    "environment": ["environment_decoration", "environment_noise", "environment_space", "environment_cleaness"],
    "dish": ["dish_portion", "dish_taste", "dish_look", "dish_recommendation"],
    "others": ["others_overall_experience", "others_willing_to_consume_again"]
}


def read_category():
    with codecs.open(os.path.join(BasePath, "category_statistical.json"), "r") as f:
        categories = json.loads(f.read())
    return categories


def combine_category():
    category_detail = dict()
    for top_category in top_categories_dict.keys():
        for k, v in read_category().items():
            is_top = k.split("_")[0]
            if is_top != top_category:
                continue
            count_sort = [v["-2"], v["-1"], v["0"], v["1"]]
            category_detail[k] = count_sort
    return category_detail


def get_top_category(category_name, categories):
    category_lst = list()
    for key in top_categories_dict[category_name]:
        category_lst.append(categories[key])
    return np.array(category_lst)


def create_histogram():
    categories = combine_category()
    for key in top_categories_dict.keys():
        top_category = get_top_category(key, categories)
        ind = np.arange(len(top_category))
        width = 0.35  # 有多少个类型，只需更改n即可
        p1 = plt.bar(ind, top_category[:, 0], width=width)
        p2 = plt.bar(ind, top_category[:, 1], width=width, bottom=top_category[:, 0])
        p3 = plt.bar(ind, top_category[:, 2], width=width, bottom=top_category[:, 0] + top_category[:, 1])
        p4 = plt.bar(ind, top_category[:, 3], width=width, bottom=top_category[:, 0] + top_category[:, 1] + top_category[:, 2])

        plt.ylabel('Num Of Train Data')
        plt.title(key)
        plt.xticks(ind, [k.replace(key + "_", "") for k in top_categories_dict[key]])
        plt.yticks(np.arange(0, 110000, 10000))
        plt.legend(
            (p1[0], p2[0], p3[0], p4[0]), ("Not mentioned", "Negative", "Neutral", 'Positive'))
        plt.savefig(os.path.join(BasePath, "image", key + ".jpg"))
        plt.close()


if __name__ == "__main__":
    create_histogram()

